package com.springcloud.zuul.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.springcloud.zuul.common.annotation.SysLog;
import com.springcloud.zuul.common.constant.ServiceCode;
import com.springcloud.zuul.common.utlis.*;
import com.springcloud.zuul.common.validator.ValidatorUtils;
import com.springcloud.zuul.common.validator.group.AddGroup;
import com.springcloud.zuul.entity.SysUserEntity;
import com.springcloud.zuul.entity.SysUserVo;
import com.springcloud.zuul.form.SysLoginForm;
import com.springcloud.zuul.service.SysCaptchaService;
import com.springcloud.zuul.service.SysUserService;
import com.springcloud.zuul.service.SysUserTokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Objects;

/**
 * Description:登陆相关
 *
 * @author zhlu
 * @date 2019/12/23 4:36 下午
 */
@RestController
@RequestMapping("/sys")
@Slf4j
@Api(tags = "登陆相关")
public class SysLoginController extends AbstractController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserTokenService sysUserTokenService;
    @Autowired
    private SysCaptchaService sysCaptchaService;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 验证码
     */
    @GetMapping("captcha.jpg")
    public void captcha(HttpServletResponse response, String uuid) throws IOException {

        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //获取图片验证码
        BufferedImage image = sysCaptchaService.getCaptcha(uuid);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }

    /**
     * 登录
     *
     * @return
     */
    @SysLog(value = "登陆", type = 2)
    @PostMapping("/login")
    @ApiOperation(notes = "登陆", value = "登陆")
    public JsonResult login(@RequestBody SysLoginForm form) throws IOException {
        ValidatorUtils.validateEntity(form, AddGroup.class);
        //用户信息
        SysUserEntity user;
        switch (form.getMethod()) {
            //普通登陆
            case 1:
                //账号密码不能为空
                if (StringUtils.isBlank(form.getLoginName()) || StringUtils.isBlank(form.getPassword())) {
                    return JsonResult.error(ServiceCode.ACCOUNT_PASSWORD);
                }
                user = sysUserService.queryByUserName(form.getLoginName());
                break;
            //手机登陆
            case 2:
                //1.先根据手机号获取验证码,是否和Redis的一样
                String redisCaptcha = redisUtils.get(form.getPhone());
                //手机号为空
                if (StringUtils.isBlank(form.getPhone())) {
                    return JsonResult.error(ServiceCode.PHONE_CANNOT_BE_EMPTY);
                }
                //验证码不正确
                if (StringUtils.isNotBlank(redisCaptcha) && !redisCaptcha.equals(form.getCaptcha())) {
                    return JsonResult.error(ServiceCode.VERIFICATION_CODE_INCORRECT);
                }
                user = sysUserService.queryByPhone(form.getPhone());
                break;
            default:
                user = sysUserService.queryByUserName(form.getLoginName());
                break;
        }

        //用户不存在
        if (Objects.isNull(user)) {
            return JsonResult.error(ServiceCode.DOES_NOT_EXIST_USER);
        }

        //账号不存在、密码错误
        if (!user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
            return JsonResult.error(ServiceCode.ACCOUNT_PASSWORD_IS_INCORRECT);
        }

        //账号锁定
        if (user.getMarkId() == 0) {
            return JsonResult.error(ServiceCode.ACCOUNT_HAS_BEEN_LOCKED);
        }

        //修改用户登陆IP与登陆时间
        UpdateWrapper<SysUserEntity>userUpdateWrapper=new UpdateWrapper<>();
        userUpdateWrapper.eq("user_id",user.getUserId());
        //获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        //设置IP地址
        user.setLoginIp(IPUtils.getIpAddr(request));
        user.setLoginTime(ConvertDateTime.getCurrentTime());

        sysUserService.update(user,userUpdateWrapper);

        //生成token，并保存到数据库
        return sysUserTokenService.createToken(user.getUserId());
    }


    /**
     * 退出
     */
    @SysLog(value = "退出")
    @PostMapping("/logout")
    @ApiOperation(notes = "退出登陆", value = "退出登陆")
    public JsonResult logout(HttpServletRequest httpRequest) {
        //从header中获取token
        String token = httpRequest.getHeader("token");

        //如果header中不存在token，则从参数中获取token
        if (StringUtils.isBlank(token)) {
            token = httpRequest.getParameter("token");
        }
        sysUserTokenService.logout(token);
        return JsonResult.actionSuccess();
    }

}
